/**
 * 
 */
package com.xbang.attendance.web.action.purchase.relateddevliery;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.xbang.attendance.entity.order.PurchaseDetails;
import com.xbang.attendance.entity.order.PurchaseOrder;
import com.xbang.attendance.entity.stock.Inventory;
import com.xbang.attendance.entity.system.SysParam;
import com.xbang.attendance.entity.system.Warehouse;
import com.xbang.attendance.service.DeliveryOrderService;
import com.xbang.attendance.service.InventoryService;
import com.xbang.attendance.utils.DeliveryJsonObject;
import com.demo2do.lighturl.annotation.Action;
import com.xbang.core.struts.support.SearchActionSupport;
import com.xbang.core.utils.DateUtils;

import edu.emory.mathcs.backport.java.util.Collections;

/**
 * @author dev.zhang
 * 
 */
public class RelatedManager extends SearchActionSupport {

	private static final long serialVersionUID = 8873433815263496064L;

	private final static Log logger = LogFactory.getLog(RelatedManager.class);
	

	@Autowired
	private DeliveryOrderService deliveryOrderService;
	@Autowired
	private InventoryService inventoryService;
	
	private List<PurchaseOrder> purchaseOrders = new ArrayList<PurchaseOrder>();
	
	
	private PurchaseOrder order;
	private Integer id;
	private Integer [] details;
	private Integer  warehouseId;
	private String orderNumber;
	
	private Integer maintenanceStationId;
	private Integer pid;
	private String doNumber;
	private String jsonList;
	private List<Warehouse> lists = new ArrayList<Warehouse>(); 
	
	
	
	/**
	 * 触发增加Action
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/purchase/related/${id}/add")
	public String add() throws Exception {
		order = deliveryOrderService.getOrderByKey(id);
		doNumber = "DO".concat(order.getMaintenanceStation().getNumber()).concat(DateUtils.format(new Date(), "yyyyMMddhhmmss"));
		//
		SysParam sysParam  = deliveryOrderService.getParamByCode("poParam");
		if(sysParam == null){
			return "add";
		}
		Set<Warehouse> wSet = order.getMaintenanceStation().getWarehouse();
		
		Set<PurchaseDetails> details = order.getPurchaseDetails();
		//Map<Integer,Warehouse> ordersMap = new HashMap<Integer, Warehouse>();
		
		for (Warehouse warehouse : wSet) {
			int temp = 0;
				 List<Inventory> list = inventoryService.getInventoryByWarehouseId(warehouse.getId()); 
				 for (PurchaseDetails purchaseDetails : details) {
					 for (Inventory inventory : list) {
						 if(sysParam.getValue().equals("1")){ //种类
							 if(inventory.getProduct().getProductCode().equals(purchaseDetails.getProduct().getProductCode())){
								 temp ++;
							 }
						 }
						 if (sysParam.getValue().equals("2")){ //数量
							 if(inventory.getProduct().getProductCode().equals(purchaseDetails.getProduct().getProductCode())){
								 if(inventory.getAmount().doubleValue() > purchaseDetails.getProductNumber().doubleValue())
									 temp += purchaseDetails.getProductNumber().intValue();
								 else{
									 temp += purchaseDetails.getProductNumber().subtract(purchaseDetails.getProductNumber().subtract(inventory.getAmount())).intValue();
								 }
							 }
						 }
					 }	
				 }
		//System.out.println(warehouse.getId()+":"+temp);		 
		 warehouse.setOrder(temp);
		 lists.add(warehouse);
		}
		
		Collections.sort(lists,new Comparator<Warehouse>(){
			@Override
			public int compare(Warehouse o1, Warehouse o2) {
				return o2.getOrder().compareTo(o1.getOrder());
			}
		});
		
		return "add";
	}
	
	@Action("/purchase/related/add/do")
	public String doAdd() throws Exception {
		JSONArray array = JSONArray.fromObject(jsonList);  
		List<DeliveryJsonObject> list = new ArrayList<DeliveryJsonObject>();   
	       for(Iterator iter = array.iterator(); iter.hasNext();){   
	           JSONObject jsonObject = (JSONObject)iter.next();
	           list.add((DeliveryJsonObject) JSONObject.toBean(jsonObject, DeliveryJsonObject.class));   
		  }   
	//    System.out.println(jsonList);
		deliveryOrderService.saveDeliveryOrder(list);
		return "r:/purchase/purchasedetails/"+list.get(0).getPid();
	}

	@Action("/purchase/related/${id}/edit")
	public String view() throws Exception {
		logger.info("request action : view");
		return "view";
	}

	@Action("/purchase/related/${id}/view")
	public String edit() throws Exception {
		logger.info("request action : edit");
		return "view";
	}

	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	@Override
	public void resetCustomerSearchCriteria() {
	}

	public PurchaseOrder getOrder() {
		return order;
	}

	public void setOrder(PurchaseOrder order) {
		this.order = order;
	}
	
	public Integer[] getDetails() {
		return details;
	}


	public void setDetails(Integer[] details) {
		this.details = details;
	}


	public Integer getWarehouseId() {
		return warehouseId;
	}


	public void setWarehouseId(Integer warehouseId) {
		this.warehouseId = warehouseId;
	}

	public String getOrderNumber() {
		return orderNumber;
	}


	public void setOrderNumber(String orderNumber) {
		this.orderNumber = orderNumber;
	}
	public Integer getMaintenanceStationId() {
		return maintenanceStationId;
	}


	public void setMaintenanceStationId(Integer maintenanceStationId) {
		this.maintenanceStationId = maintenanceStationId;
	}




	public DeliveryOrderService getDeliveryOrderService() {
		return deliveryOrderService;
	}


	public void setDeliveryOrderService(DeliveryOrderService deliveryOrderService) {
		this.deliveryOrderService = deliveryOrderService;
	}


	public Integer getPid() {
		return pid;
	}


	public void setPid(Integer pid) {
		this.pid = pid;
	}


	public String getDoNumber() {
		return doNumber;
	}


	public void setDoNumber(String doNumber) {
		this.doNumber = doNumber;
	}


	public List<PurchaseOrder> getPurchaseOrders() {
		return purchaseOrders;
	}


	public void setPurchaseOrders(List<PurchaseOrder> purchaseOrders) {
		this.purchaseOrders = purchaseOrders;
	}

	public String getJsonList() {
		return jsonList;
	}

	public void setJsonList(String jsonList) {
		this.jsonList = jsonList;
	}

	public List<Warehouse> getLists() {
		return lists;
	}

	public void setLists(List<Warehouse> lists) {
		this.lists = lists;
	}
	
}

